package cc.linker.steplink.crm.merchant.controller;

import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchant.util.ExcelDataUtil;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchanth5.service.VipExchangeService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * pc端兑换相关业务
 * @author huhj
 */
@Slf4j
@RestController
@RequestMapping("/vipExchange")
public class VipExchangeController {

    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private VipExchangeService vipExchangeService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取列表
     * @param pageIndex
     * @param pageSize
     * @param exchangeName
     * @param status
     * @return
     */
    @GetMapping("/getList")
    public PageInfo getList(HttpServletRequest request,
                                    @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                    @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                    @RequestParam(value = "exchangeName", defaultValue = "") String exchangeName,
                                    @RequestParam(value = "status", defaultValue = "", required = false) Integer status
    ) throws Exception{
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        if(!StringUtils.isEmpty(exchangeName)){
            exchangeName = URLDecoder.decode(exchangeName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            exchangeName = exchangeName.replaceAll("%", "/%");
                param.put("exchangeName", exchangeName);
            }
        param.put("status", status);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(vipExchangeService.getList(param));
    }

    /**
     * 新增编辑兑换
     * @param request
     * @param param
     */
    @PostMapping("/saveExchange")
    public void saveVip( HttpServletRequest request,@RequestBody Map<String, Object> param ){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        param.put("orgId", orgId);
        vipExchangeService.saveExchange(param);
    }

    /**
     * 获取兑换详情
     * @param exchangeId
     * @param exchangeId
     */
    @GetMapping("/getInfo")
    public Map getInfo(Long exchangeId){
        return vipExchangeService.getInfo(exchangeId);
    }
    /**
     * 删除兑换
     * @param param
     */
    @PostMapping("/deleteExchange")
    public void deleteExchange(@RequestBody Map<String, Object> param){
        vipExchangeService.deleteExchange(param);
    }

    /**
     * 修改兑换状态
     * @param param
     */
    @PostMapping("/updateStatus")
    public void updateStatus(@RequestBody Map<String, Object> param){
        vipExchangeService.updateStatus(param);
    }


    /**
     * 获取领取列表
     * @param pageIndex
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param customerName
     * @param customerPhone
     * @return
     */
    @GetMapping("/getExChangeList")
    public PageInfo getExChangeList(HttpServletRequest request,
                            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                            @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                            @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                            @RequestParam(value = "exchangeId", defaultValue = "") String exchangeId,
                            @RequestParam(value = "customerName", defaultValue = "", required = false) String customerName,
                            @RequestParam(value = "customerPhone", defaultValue = "", required = false) String customerPhone
    ) throws Exception{
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("exchangeId", exchangeId);
        if(!StringUtils.isEmpty(startTime)){
            param.put("startTime", startTime+" 00:00:00");
        }
        if(!StringUtils.isEmpty(endTime)){
            param.put("endTime", endTime+" 23:59:59");
        }

        if(!StringUtils.isEmpty(customerName)){
            customerName = URLDecoder.decode(customerName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            customerName = customerName.replaceAll("%", "/%");
            param.put("customerName", customerName);
        }
        if(!StringUtils.isEmpty(customerPhone)){
            param.put("customerPhone", customerPhone);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(vipExchangeService.getExChangeList(param));
    }

    /**
     * 导出兑换码判断是否生成中
     */
    @PostMapping("/exportExchangeCodeCheck")
    public void exportExchangeCode(@RequestBody Map<String, Object> param){
        if(StringUtils.isEmpty(param.get("exchangeId"))){
            throw GlobalException.build("参数错误");
        }
        String exchangeIdS= param.get("exchangeId").toString();
        if(exchangeIdS.length()<=4){
            switch (exchangeIdS.length()){
                case 1:exchangeIdS="000"+exchangeIdS;
                    break;
                case 2:exchangeIdS="00"+exchangeIdS;
                    break;
                case 3:exchangeIdS="0"+exchangeIdS;
                    break;
                default:
                    break;
            }
        }
        String exchangeCodeDoing = stringRedisTemplate.opsForValue().get("exchangeCode:exchangeCodeDoing_"+exchangeIdS);
        if(!StringUtils.isEmpty(exchangeCodeDoing)){
            throw GlobalException.build("兑换码正在生成中，请稍后再试……");
        }
    }

    /**
     * 导出兑换码
     * @param response
     */
    @GetMapping("/exportExchangeCode")
    public void exportExchangeCode(Long exchangeId,String exchangeName,Integer exchangeType,HttpServletResponse response){
        if(exchangeType==null || exchangeId==null){
            throw GlobalException.build("参数错误");
        }
        String fileName = exchangeName+"兑换码列表";
        vipExchangeService.exportExchangeCode(exchangeId,exchangeType,fileName,response);
    }


    /**
     * 导入自定义兑换列表列表
     * @param request
     * @param file
     */
    @PostMapping(value = "/importExcelData")
    @ResponseBody
    public Map<String,String> importExcelData(MultipartFile file, HttpServletRequest request){
        List<Map<String,String>> list;
        try{
            list = ExcelDataUtil.getAllByExcel(file);
        }catch (Exception e){
            e.printStackTrace();
            throw GlobalException.build("导入表格格式错误，与导入模板不符");
        }
        List<Map<String,String>> ableList = new ArrayList<>();
        if(list!=null && list.size()>0){
            Map title = list.get(0);
            if(title.size()!=2 || !"手机号".equals(title.get("0")) || !"兑换时长(天)".equals(title.get("1"))){
                throw GlobalException.build("导入表格格式错误，与导入模板不符");
            }
            list.remove(0);
            for(Map<String,String> map : list){
                //exchangeCodesList
                Map exchangeCode = new HashMap();
                exchangeCode.put("exchangePhone",map.get("0"));
                exchangeCode.put("exchangeDays",map.get("1"));
                if(StringUtils.isEmpty(exchangeCode.get("exchangePhone")) || StringUtils.isEmpty(exchangeCode.get("exchangeDays"))){
                    continue;
                }
                String exchangePhone = exchangeCode.get("exchangePhone").toString();
                String exchangeDays = exchangeCode.get("exchangeDays").toString();
                if(!this.isNumer(exchangePhone) || exchangePhone.length()!=11){
                    //手机号格式错误
                    continue;
                }
                if(!this.isNumer(exchangeDays) || Integer.valueOf(exchangeDays)>99999 ||  Integer.valueOf(exchangeDays)<=0){
                   //兑换天数格式错误
                    continue;
                }
                ableList.add(exchangeCode);
            }
        }
        Map res = new HashMap();
        res.put("ableList",ableList);
        res.put("ableCount",ableList.size());
        res.put("unableCount",list.size() - ableList.size());
        return res;
    }


    /**
     * 导出自定义兑换模板
     * @param response
     */
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response){
        String fileName = "自定义兑换导入数据模板";
        vipExchangeService.exportTemplate(fileName,response);
    }

    public boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
